import React  from 'react';
import ReactDOM from 'react-dom';
// import App from './App.js'
import {createStore} from 'redux'
import {Provider,connect} from 'react-redux'

class Counter extends React.Component{
  render(){
    // console.log(this.props);
    //计数,通过stroe的state传给props。直接通过props就可以将state的数据进行获取
    const value = this.props.value;
    //将修改的事件或者方法传入到props
    const onAddClick = this.props.onAddClick;
    //等同于vuex的Mutation State
    return(
      <div>
        <h1>计数的数量：{value}</h1>
        <button onClick={onAddClick}> + </button>
        <button onClick={this.props.onAddClick5}> +5 </button>
      </div>
    )

  }
}

const addAction = {
  type: 'add'
}

let ActionFnobj={
  add:function(state){
    state.num++
    return state
  },
  addNum: function(state,action){
  
    state.num = state.num + action.num;
    return state
  }
}


function reducer (state = {num:0},action){
  console.log(state);
  console.log(action);
  if (action.type.indexOf('redux') === -1) {
    state = ActionFnobj[action.type](state,action)
    return {...state}
  }else{
    return state
  }
  
 
}
const store = createStore(reducer)

//将状态映射到props函数
function mapStateToProps(state){
  return{
    value: state.num
  }
}
//将修改state数据的方法，映射到props,，默认会传入dispach方法
function mapDispatchToProps(dispatch){
  return {
    onAddClick:()=>{
      dispatch(addAction)
    },
    onAddClick5:()=>{
      //动作类型
    dispatch({type:'addNum',num:5})
    }
  }
}
//将上面的这两个方法，将数据仓库的state和修改state的方法映射到组件上，形成新的组件
const App = connect(
  mapStateToProps,
  mapDispatchToProps
)(Counter)



ReactDOM.render(
  <Provider store={store}>
    <App></App>
  </Provider>,
  document.querySelector('#root')
 
);



